//
//  WetLandBookingOrderViewController.m
//  homeland
//
//  Created by SunShine on 14-1-23.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//

#import "WetLandBookingOrderViewController.h"
#import "BookingStepperCell.h"
#import "BookingDateCell.h"
#import "CKCalendarView.h"
#import "BookingInputCell.h"
#import "BookingDateCell.h"
#import "WetlandService.h"
#import "WetLandOrderDetailViewController.h"
#import "UserInfoService.h"


#define BOOKING_NAME_FIELD_TAG 1001
#define BOOKING_PHONE_FIELD_TAG 1002
#define BOOKING_PIAO_FIELD_TAG 1003
#define INPUT_VIEW_OFFSET 160.0

@interface WetLandBookingOrderViewController () <CKCalendarDelegate, UITextFieldDelegate>

@property (strong, nonatomic) CKCalendarView *calendar;
@property (strong, nonatomic) UIView *cover;
@property (strong, nonatomic) NSDate *selectedDate;
@property (strong, nonatomic) NSArray *allowList;
@property (strong, nonatomic) NSDateFormatter *formatter;

@property (strong, nonatomic) NSMutableArray *countList;
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *phone;
@property (strong, nonatomic) NSString *ticketCount;//剩余票数
//@property (strong, nonatomic) NSArray<NSIndexPath>* arrayIndex;

@property (strong, nonatomic) IBOutlet UITableView *tableView;
- (IBAction)commitButtonAction:(id)sender;
@end

@implementation WetLandBookingOrderViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//     arrayIndex = [NSArray<NSIndexPath> AL]
    // Do any additional setup after loading the view from its nib.
    self.title = @"订单填写";
    self.ticketCount=@"   ";
    self.countList = [NSMutableArray array];
    for (int i = 0, count = self.ticketsList.count; i < count; i ++) {
        [self.countList addObject:[NSNumber numberWithInteger:0]];
    }
    self.name = [UserInfoService getUserInfoService].userInfo.userName;
    self.phone = [UserInfoService getUserInfoService].userInfo.mobile;
    //初始化日历相关
    self.formatter = [[NSDateFormatter alloc] init];
    [self.formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8*3600]];
    [self.formatter setDateFormat:@"yyyy-MM-dd"];
    self.cover = [[UIView alloc] initWithFrame:self.view.frame];
    self.cover.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    self.cover.hidden = YES;
    [self.view addSubview:self.cover];
    self.calendar = [[CKCalendarView alloc] initWithStartDay:startSunday frame:CGRectMake(0, 30, 320, 250)];
    self.calendar.delegate = self;
    self.calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    self.calendar.hidden = YES;
    [self.view addSubview:self.calendar];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//分为三部份
#pragma mark - Table Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return (self.ticketsList.count + 3);
}
//每组几条item
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section < self.ticketsList.count) {
        //份数选择
        return 1;
    } else if (section == self.ticketsList.count) {
        //选择日期
        return 1;
    } else if (section == 2) {
        //联系人信息
        return 2;
    }else{
        return 1;
    }
}
//返回视图
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"indexPath.section = %d",indexPath.section);
    NSLog(@"self.ticketsList.count = %d",self.ticketsList.count);
    if (indexPath.section < self.ticketsList.count) {
        //份数选择
        BookingStepperCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"BookingStepperCell" owner:self options:nil] objectAtIndex:0];
//        NSDictionary *dic = [self.ticketsList objectAtIndex:indexPath.section];
        cell.titleLabel.text = @"购买份数";
        //初始化stepper
        cell.stepper.tag = indexPath.section;
        cell.stepper.Current = [[self.countList objectAtIndex:indexPath.section] integerValue];
        cell.stepper.Step = 1;
        cell.stepper.Minimum = 1;
        cell.stepper.Maximum = 10;
        cell.stepper.NumDecimals = 0;
        cell.stepper.IsEditableTextField = NO;
//        cell.stepper.textField.inputAccessoryView = [self getInputAccessoryView];
//        cell.stepper.textField.tag = indexPath.section;
//        cell.stepper.textField.delegate = self;
        [cell.stepper addTarget:self action:@selector(stepperValueChanged:) forControlEvents:UIControlEventValueChanged];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else if (indexPath.section == self.ticketsList.count) {
        //选择日期
        BookingDateCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"BookingDateCell" owner:self options:nil] firstObject];
        cell.titleLabel.text = @"使用日期";
        if (self.selectedDate == nil) {
            cell.dateLabel.text = @"请选择日期";
            cell.dateLabel.textColor = [UIColor lightGrayColor];
        } else {
            cell.dateLabel.text = [self.formatter stringFromDate:self.selectedDate];
            cell.dateLabel.textColor = [UIColor blackColor];
            //设置完日期在这里请求后台并设置票数
            
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    } else if (indexPath.section == 2){
        //联系人信息
        BookingInputCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"BookingInputCell" owner:self options:nil] firstObject];
        if (indexPath.row == 0) {
            //姓名
            cell.titleLabel.text = @"取票人";
            cell.inputField.tag = BOOKING_NAME_FIELD_TAG;
            cell.inputField.text = self.name;
        } else if(indexPath.row == 1){
            //手机号
            cell.titleLabel.text = @"手机号码";
            cell.inputField.tag = BOOKING_PHONE_FIELD_TAG;
            cell.inputField.keyboardType = UIKeyboardTypePhonePad;
            cell.inputField.text = self.phone;
        }
        cell.inputField.inputAccessoryView = [self getInputAccessoryView];
        cell.inputField.delegate = self;
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        BookingDateCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"BookingDateCell" owner:self options:nil] firstObject];
        if (indexPath.row == 0) {
                 //剩余票数
            cell.titleLabel.text = @"剩余票数";
            NSLog(@"----%@",self.ticketCount);
            cell.dateLabel.text = self.ticketCount;
 
 
            if (self.ticketCount == nil) {
                cell.dateLabel.text = @" ";
                cell.dateLabel.textColor = [UIColor lightGrayColor];
            } else {
                cell.dateLabel.text = self.ticketCount;
                cell.dateLabel.textColor = [UIColor blackColor];
                //设置完日期在这里请求后台并设置票数
                
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//            if (self.ticketCount == nil || [self.ticketCount isEqualToString:@""]) {
//                cell.hidden=YES;
//            }else{
//                cell.hidden=NO;
//            }
            
        return cell;
        }
        
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == self.ticketsList.count) {
        //选择日期
        self.cover.hidden = NO;
        [self.view bringSubviewToFront:self.cover];
        self.calendar.hidden = NO;
        [self.view bringSubviewToFront:self.calendar];
        
//        self.allowList = @[[NSDate date], [NSDate dateWithTimeIntervalSinceNow:3600*24], [NSDate dateWithTimeIntervalSinceNow:3600*24*2], [NSDate dateWithTimeIntervalSinceNow:3600*24*3]];
        self.allowList = @[[NSDate dateWithTimeIntervalSinceNow:3600*24], [NSDate dateWithTimeIntervalSinceNow:3600*24*2], [NSDate dateWithTimeIntervalSinceNow:3600*24*3]];
        [self.calendar reloadData];
        [self.calendar selectDate:self.selectedDate makeVisible:YES];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section < self.ticketsList.count) {
        //份数选择
        return 40.0;
    } else {
        return 1.0;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section < self.ticketsList.count) {
        //份数选择
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40.0)];
        view.backgroundColor = [UIColor clearColor];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 20.0)];
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label];
        NSDictionary *dic = [self.ticketsList objectAtIndex:section];
        label.text = [dic objectForKey:@"cname"];
        return view;
    }
    
    else {
        return nil;
    }
}

#pragma mark - Stepper Action
-(void)stepperValueChanged:(id)sender
{
    TextStepperField *stepper = (TextStepperField *)sender;
    [self.countList replaceObjectAtIndex:stepper.tag withObject:[NSNumber numberWithInteger:stepper.Current]];
}

#pragma mark - Date Logic
//判断传入的日期是否允许选择
-(BOOL)isDateAllowed:(NSDate *)date
{
    for (NSDate* allowedDate in self.allowList) {
        if ([self date:allowedDate isSameDayAsDate:date]) {
            return YES;
        }
    }
    return NO;
}

//判断传入的日期是否为同一天
- (BOOL)date:(NSDate *)date1 isSameDayAsDate:(NSDate *)date2 {
    // Both dates must be defined, or they're not the same
    if (date1 == nil || date2 == nil) {
        return NO;
    }
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *day = [calendar components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date1];
    NSDateComponents *day2 = [calendar components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date2];
    return ([day2 day] == [day day] && [day2 month] == [day month] && [day2 year] == [day year] && [day2 era] == [day era]);
}

//判断两个日期的月份间隔
-(NSInteger)calculateMonthIntervalFromDate1:(NSDate *)date1 ToDate2:(NSDate*)date2
{
    if (date1 == nil || date2 == nil) {
        return 0;
    }
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *day = [calendar components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date1];
    NSDateComponents *day2 = [calendar components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date2];
    return ([day year]*12+[day month]) - ([day2 year]*12+[day2 month]);
}

//判断传入的日期是否在月底3天
-(BOOL)isLastDaysInMonth:(NSDate *)date
{
    NSDate *dateNew = [date dateByAddingTimeInterval:3*24*3600];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *day = [calendar components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
    NSDateComponents *day2 = [calendar components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:dateNew];
    return [day month] != [day2 month];
}

#pragma mark - Calender Delegate
-(void)calendar:(CKCalendarView *)calendar configureDateItem:(CKDateItem *)dateItem forDate:(NSDate *)date
{
    if ([self isDateAllowed:date]) {
        //可选日期
        dateItem.backgroundColor = [UIColor whiteColor];
        dateItem.textColor = [UIColor blackColor];
    } else {
        //不可选日期
        dateItem.backgroundColor = [UIColor lightGrayColor];
        dateItem.textColor = [UIColor darkGrayColor];
    }
}

-(BOOL)calendar:(CKCalendarView *)calendar willSelectDate:(NSDate *)date
{
    if ([self isDateAllowed:date]) {
        self.selectedDate = date;
        return YES;
    } else {
        return NO;
    }
}

-(BOOL)calendar:(CKCalendarView *)calendar willDeselectDate:(NSDate *)date
{
    NSLog(@"will Deselect Date:%@", date);
    if ([date isEqualToDate:self.selectedDate]) {
        [self calendar:calendar didSelectDate:date];
    };
    return NO;
}
//设置返回来时间值
-(void)calendar:(CKCalendarView *)calendar didSelectDate:(NSDate *)date
{
    if (date == nil) {
        return;
    }
    self.selectedDate = date;
    self.cover.hidden = YES;
    self.calendar.hidden = YES;
    
    [self.tableView reloadData];
    //请求后台。设置剩余票数 self.ticketCount=@"";<#(NSString *)#>
    [[WetlandService new] getTicketsCount:[self.formatter stringFromDate:self.selectedDate]
     Success:^(NSString *data) {
         int count = [data intValue];
         if(count < 300){
             count = 300 - count;
             self.ticketCount= [NSString stringWithFormat:@"%d",count];
         }else{
             self.ticketCount=@"票已预订完";
         }
        [self.tableView reloadData];
    } Failure:^(NSString *msg) {}];
    
    
   
//    NSIndexPath* indexPath = [self.tableView indexPathForSelectedRow];
//     [self.tableView cellForRowAtIndexPath:
//    [self.tableView tableFooterView].hidden=NO;
//    self.tableView.indexPathForSelectedRow
//   NSIndexPath *indexPath = [self.tableView delegate ] ;
//    
}

-(BOOL)calendar:(CKCalendarView *)calendar willChangeToMonth:(NSDate *)date
{
    NSLog(@"判断显示日期%@", date);
    NSInteger interval = [self calculateMonthIntervalFromDate1:date ToDate2:[NSDate date]];
    NSLog(@"月份间隔:%d", interval);
    if (interval <= -1) {
        NSLog(@"不支持选择早于当前月的数据");
        return NO;
    }
    if (interval >= 2) {
        NSLog(@"不支持再下一个的数据选择");
        return NO;
    }
    if (![self isLastDaysInMonth:[NSDate date]]&&interval == 1) {
        NSLog(@"当前不是月末，不需要显示下个月");
        return NO;
    }
    return YES;
}

#pragma mark - Text Delegate
//开始输入的时候把整个界面向上移动
-(void)textFieldDidBeginEditing:(UITextView *)textView
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.3f];
    CGRect frame = self.view.frame;
    frame.size.height = frame.size.height - INPUT_VIEW_OFFSET;
    self.view.frame = frame;
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:textView.tag-1001 inSection:self.ticketsList.count+1] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    [UIView commitAnimations];
    _tableView.scrollEnabled = NO;
}

//输入结束的时候把整个界面向下移动，这个能恢复正常
-(void)textFieldDidEndEditing:(UITextView *)textView
{
    //详细地址才需要移动
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.3f];
    CGRect frame = self.view.frame;
    frame.size.height = frame.size.height + INPUT_VIEW_OFFSET;
    self.view.frame = frame;
    [UIView commitAnimations];
    _tableView.scrollEnabled = YES;
    if (textView.tag == BOOKING_NAME_FIELD_TAG) {
        self.name = textView.text;
    }
    if (textView.tag == BOOKING_PHONE_FIELD_TAG) {
        self.phone = textView.text;
    }
    if (textView.tag == BOOKING_PIAO_FIELD_TAG) {
        self.ticketCount = textView.text;
    }
}

#pragma mark - Button
- (IBAction)commitButtonAction:(id)sender
{
    [self.view endEditing:YES];
    NSLog(@"准备提交订单");
    NSInteger allHuman = 0;
    NSMutableArray *list = [NSMutableArray array];
    for (int i = 0, count = self.ticketsList.count; i < count; i ++) {
        NSInteger num = [[self.countList objectAtIndex:i] integerValue];
        if (num > 0) {
            NSDictionary *ticket = [self.ticketsList objectAtIndex:i];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[ticket objectForKey:@"cmemo"], @"cmemo", [ticket objectForKey:@"cname"], @"cticketname", [ticket objectForKey:@"fprice"], @"fprice", [NSNumber numberWithInteger:num], @"nhuman", nil];
            [list addObject:dic];
            allHuman = allHuman + num;
        }
    }
    if (list.count == 0) {
        [self showAlertWithTitle:@"错误" Msg:@"选择的总票数不能为0"];
        return;
    }
    if (allHuman > 3) {
        [self showAlertWithTitle:@"错误" Msg:@"目前不允许一次订票超过3张"];
        return;
    }
    if (self.selectedDate == nil) {
        [self showAlertWithTitle:@"错误" Msg:@"请选择日期"];
        return;
    }
    if (isBlankString(self.name)) {
        [self showAlertWithTitle:@"错误" Msg:@"请输入取票人姓名"];
        return;
    }
    if (isBlankString(self.phone)) {
        [self showAlertWithTitle:@"错误" Msg:@"请输入手机号码"];
        return;
    }
    [self startLoadingViewWithText:@"正在提交订单"];
    [[WetlandService new] commitOrderWithCount:allHuman Tickets:list Name:self.name Phone:self.phone PreseTime:[self.formatter stringFromDate:self.selectedDate] Success:^(NSString *presellid) {
        NSLog(@"响应的订单号为:%@", presellid);
        [self stopLoadingView];
        WetLandOrderDetailViewController *detailVC = [[WetLandOrderDetailViewController alloc] initWithNibName:@"WetLandOrderDetailViewController" bundle:nil];
        detailVC.orderId = nil;
        detailVC.state = @"0";
        detailVC.presellid = presellid;
        detailVC.config = [NSDictionary dictionaryWithObject:presellid forKey:@"presellid"];
        [self.navigationController pushViewController:detailVC animated:YES];
    } Failure:^(NSString *msg) {
        [self stopLoadingView];
        [self showAlertWithTitle:@"错误" Msg:msg];
    }];
}
@end
